package controllers

import (
    "beego_background_framework/models"
    "beego_background_framework/utils"
    "github.com/astaxie/beego/orm"
    "strings"
)

//角色组
type AdminGroupController struct {
    BaseController
}

func (c *AdminGroupController) Index(){
    o := orm.NewOrm()
    var list[]*models.AdminGroup
    _, _ = o.QueryTable(new(models.AdminGroup)).All(&list)

    c.Data["list"] = list
    c.SetTpl("admin_group/index.html")
}

func (c *AdminGroupController) Create()  {

    //设置权限列表
    c.Data["treeMenus"] = c.GetRuleList()
    c.SetTpl("admin_group/create.html")
}

func (c *AdminGroupController) Add()  {
    var adminGroup models.AdminGroup
    var rules []string
    _ = c.Ctx.Input.Bind(&adminGroup.Name, "name")
    _ = c.Ctx.Input.Bind(&adminGroup.Remark, "remark")
    _ = c.Ctx.Input.Bind(&rules, "rule")
    adminGroup.Rules = strings.Join(utils.TrimSlice(rules),",")
    adminGroup.Status = 1

    o := orm.NewOrm()
    _, err := o.Insert(&adminGroup)
    if err != nil{
        c.ApiError(err.Error(),nil)
    }

    c.ApiSuccess("操作成功",nil)
}

func (c *AdminGroupController) Edit()  {
    id, err := c.GetUint64(":id")
    if err != nil{
        c.RequestError("参数不正确","/admin/group")
    }
    adminGroup := models.AdminGroup{Id: uint(id)}
    o := orm.NewOrm()
    err = o.Read(&adminGroup)
    if err != nil{
        c.RequestError("找不到该条数据","/admin/group")
    }
    //设置权限列表
    c.Data["treeMenus"] = c.GetRuleList()
    var rules []string
    if adminGroup.Rules != "*"{
        rules = strings.Split(adminGroup.Rules,",")
    }
    c.Data["info"] = adminGroup
    c.Data["rules"] = rules
    c.SetTpl("admin_group/edit.html")
}

func (c *AdminGroupController) Update()  {
    var adminGroup models.AdminGroup
    o := orm.NewOrm()
    _ = c.Ctx.Input.Bind(&adminGroup.Id, ":id")
    err := o.Read(&adminGroup)
    if err != nil{
        c.ApiError("查询失败",nil)
    }
    _ = c.Ctx.Input.Bind(&adminGroup.Name, "name")
    _ = c.Ctx.Input.Bind(&adminGroup.Remark, "remark")
    var rules []string
    _ = c.Ctx.Input.Bind(&rules, "rule")
    adminGroup.Rules = strings.Join(utils.TrimSlice(rules),",")
    _, err = o.Update(&adminGroup)
    if err != nil{
        c.ApiError("更新失败",nil)
    }

    c.ApiSuccess("操作成功",nil)
}

func (c *AdminGroupController) Destroy(){
    id, _ := c.GetUint64(":id")
    o := orm.NewOrm()
    if num,err :=o.Delete(&models.AdminGroup{Id: uint(id)});err == nil{
        if num > 0{
            c.ApiSuccess("操作成功",nil)
        }
    }
    c.ApiError("操作失败",nil)
}